package cn.com.generaldata.os.ws.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.IndicatorAccount;
import cn.com.generaldata.os.pojo.IndicatorData;
import cn.com.generaldata.os.service.intf.IndicatorServiceInterface;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.AreaVO;
import cn.com.generaldata.os.vo.IndicatorAccountVO;
import cn.com.generaldata.os.vo.IndicatorDataVO;
import cn.com.generaldata.os.vo.IndicatorInputVO;
import cn.com.generaldata.os.vo.ResultVO;
import edu.emory.mathcs.backport.java.util.Arrays;

@Component
@InjectName
public class IndicatorWS{

	private static Logger logger = LoggerFactory.getLogger(IndicatorWS.class);

	@Autowired
	private IndicatorServiceInterface indicatorService;

	@Autowired
	private IndustryWS industryService;
	
	@Autowired
	private ReportWS reportService;
	
	@Autowired
	private AreaWS areaService;	
	
	@Autowired
	private VersionWS versionService;
	
	@Autowired
	private UnitWS unitService;

	@At("/audit/importIndicator/?")
	@Ok("jsp:/static/ocean/unit/uploadOk")
	@AdaptBy(type = UploadAdaptor.class)
	public void importIndicator(String uid, @Param("fileField") TempFile tempFile, HttpServletRequest request) {
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		
		String fileType = "";
		String fileName = tempFile.getMeta().getFileLocalName();
		File file = tempFile.getFile();
		
		if (fileName!=null&&fileName.length()>0&&fileName.lastIndexOf(".")>-1){
			fileType = fileName.substring(fileName.lastIndexOf("."));
		}
		
		String[] split = fileName.split(fileType);
		String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		FileInputStream in = null;
		byte[] content = null;
		try {
			in = new FileInputStream(file);
			content = new byte[in.available()];
			in.read(content);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (content != null) {
			File file1 = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file1);
				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("上传文件出错", e);
			}

			String importIndicator = "";
			if ("codeUp".equals(uid))
				importIndicator = indicatorService.importGDPCode(file, uid);
			else if ("consumpUp".equals(uid))
				importIndicator = indicatorService.importConsumpValue(file, uid);
			else if ("baseUp".equals(uid))
				importIndicator = indicatorService.importBaseValue(file, uid);
			else
				importIndicator = indicatorService.importIndicator(file, uid);
			// ReportExcelSectionVO sectionInfo = reportTmplate.getReportExcelSectionInfo(file, reportTypeId);
			// // sectionInfo.getReportFootEndRow();
			// reportService.import_report(user, reportProxyId, rType, timeType, yearType, timeDate, unitIndustryId,
			// reportVersion, quarterDate, file, sectionInfo, lasttimeReport);

			request.setAttribute("msg", importIndicator);
		}
	}
	

	@At("/audit/findIndicatorInputs")
	@Ok("json")
	public ResultVO<IndicatorInputVO> findIndicatorInputs(@Param("indicatorType") String type, @Param("indicatorName") String name, @Param("frequency") Integer frequency, @Param("page") Integer pageNum, @Param("rows") int rows) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, rows);
		}else{
			return null;
		}
		cn.com.generaldata.os.paging.Result list = indicatorService.findIndicatorInputs(type, name, frequency, page);
		ResultVO<IndicatorInputVO> result = new ResultVO<IndicatorInputVO>();
		List<IndicatorInputVO> operationResult = new ArrayList<IndicatorInputVO>();
		if (list != null) {
			operationResult = (List<IndicatorInputVO>) list.getOperationResult();
			result.setPageNumber(list.getPageNumber());
			result.setPageSize(list.getPageSize());
			result.setTotalCount(list.getTotalCount());
		} else {
			result.setPageNumber(page.getPageNumber());
			result.setPageSize(page.getPageSize());
			result.setTotalCount(0);
		}
		result.setOperationResult(operationResult);

		return result;
	}

	@At("/audit/createIndicator")
	@Ok("json")
	public String createIndicator(@Param("..") IndicatorDataVO indiVo) {
		return indicatorService.createIndicator(indiVo);
	}

	// 取得指标类型
	
	public List<SystemCodedic> queryType() {
		return indicatorService.queryType();
	}

	/**
	 * 查询指标数据
	 * */
	@At("/audit/queryIndicatorData")
	@Ok("json")
	public ResultVO<IndicatorDataVO> queryIndicatorData(@Param("..") IndicatorDataVO indiVo, @Param("page") Integer pageNum, @Param("rows") int rows) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, rows);
		}
		cn.com.generaldata.os.paging.Result list = indicatorService.queryIndicatorData(indiVo, page);
		ResultVO<IndicatorDataVO> result = new ResultVO<IndicatorDataVO>();
		List<IndicatorDataVO> operationResult = new ArrayList<IndicatorDataVO>();
		if (list != null) {
			operationResult = (List<IndicatorDataVO>) list.getOperationResult();
			result.setPageNumber(list.getPageNumber());
			result.setPageSize(list.getPageSize());
			result.setTotalCount(list.getTotalCount());
		} else {
			result.setPageNumber(page.getPageNumber());
			result.setPageSize(page.getPageSize());
			result.setTotalCount(0);
		}
		result.setOperationResult(operationResult);
		return result;

	}

	/**
	 * 查询核算指标
	 */
	@At("/audit/indicatorAccount")
	@Ok("json")
	public ResultVO<IndicatorAccountVO> queryIndicatorAccount(@Param("..") IndicatorAccountVO indiVo, @Param("page") Integer pageNum, @Param("sort") String sort, @Param("order") String order, @Param("rows") int rows) {

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, rows);
		}else{
			page = new Page(1, rows);
		}
		
		cn.com.generaldata.os.paging.Result list = indicatorService.queryIndicatorAccount(indiVo, page, sort, order);
		ResultVO<IndicatorAccountVO> result = new ResultVO<IndicatorAccountVO>();
		List<IndicatorAccountVO> operationResult = new ArrayList<IndicatorAccountVO>();
		if (list != null) {
			operationResult = (List<IndicatorAccountVO>) list.getOperationResult();
			result.setPageNumber(list.getPageNumber());
			result.setPageSize(list.getPageSize());
			result.setTotalCount(list.getTotalCount());
		} else {
			result.setPageNumber(page.getPageNumber());
			result.setPageSize(page.getPageSize());
			result.setTotalCount(0);
		}
		result.setOperationResult(operationResult);
		return result;

	}
	
	/**
	 * 进入查询核算指标页面
	 */
	@At("/audit/indicatorAccountToPage")
	@Ok("jsp:/static/ocean/audit/indicatorAccount")
	public void queryIndicatorAccountToPage(HttpServletRequest request) {
		
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型

	}
	
	/**
	 * 进入核算指标维护页面
	 */
	@At("/audit/indicatorInputToPage")
	@Ok("jsp:/static/ocean/audit/indicatorInput")
	public void queryIndicatorInputToPage(HttpServletRequest request) {
		
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型
		request.setAttribute("indicatorType", indicatorService.queryType());	//指标分类
		request.setAttribute("industryList", industryService.queryAllDLIndustries());	//产业分类
	}
	
	/**
	 * 进入指标录入页面
	 */
	@At("/audit/indicatorAddToPage")
	@Ok("jsp:/static/ocean/audit/indicatorAdd")
	public void indicatorAddToPage(HttpServletRequest request) {
		
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型
		request.setAttribute("indicatorType", indicatorService.queryType());	//指标分类
		request.setAttribute("industryList", industryService.queryAllDLIndustries());	//产业分类
	}
	
	/**
	 * 进入指标项查询页面
	 */
	@At("/audit/indicatorAddSelectToPage")
	@Ok("jsp:/static/ocean/audit/indicatorAddSelect")
	public void indicatorAddSelectToPage(HttpServletRequest request) {
		request.setAttribute("indicatorType", indicatorService.queryType());	//指标分类
	}

//	/**
//	 * 查询核算指标
//	 */
//	
//	public ResultVO<IndicatorAccountVO> queryIndicatorAccountSort(IndicatorAccountVO indiVo, Integer pageNum,String sort) {
//		Page page = null;
//		if (pageNum != null) {
//			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
//		}
//		cn.com.generaldata.os.paging.Result list = indicatorService.queryIndicatorAccount(indiVo, page,sort);
//		ResultVO<IndicatorAccountVO> result = new ResultVO<IndicatorAccountVO>();
//		List<IndicatorAccountVO> operationResult = new ArrayList<IndicatorAccountVO>();
//		if (list != null) {
//			operationResult = (List<IndicatorAccountVO>) list.getOperationResult();
//			result.setPageNumber(list.getPageNumber());
//			result.setPageSize(list.getPageSize());
//			result.setTotalCount(list.getTotalCount());
//		} else {
//			result.setPageNumber(page.getPageNumber());
//			result.setPageSize(page.getPageSize());
//			result.setTotalCount(0);
//		}
//		result.setOperationResult(operationResult);
//		return result;
//
//	}
	
	/**
	 * 删除选中的指标
	 * */
	@At("/audit/removeIndicator")
	@Ok("json")
	public String removeIndicator(@Param("ids") String delIds) {
		
		List ids = Arrays.asList(delIds.split(","));
		
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);
			indicatorService.removeIndicator(arrIds);
		}
		return "success";
	}

	
	public Double checkIndicator(int id, String areaId, int timeTYpe, int year) {
		return indicatorService.checkIndicator(id, areaId, timeTYpe, year);
	}

	
	public IndicatorDataVO checkIndicatorExists(int id, String areaId, Integer timeType, Integer yearType, int year,
			Integer quarter) {
		IndicatorData indicatorData = indicatorService.checkIndicatorExists(id, areaId, timeType, yearType, year,
				quarter);
		if (indicatorData == null) {
			return null;
		}
		IndicatorDataVO indicator = BeanMapper.map(indicatorData, IndicatorDataVO.class);
		return indicator;
	}

	@At("/audit/checkUpdateIndicator")
	@Ok("json")
	public boolean checkUpdateIndicator(@Param("id") String id, @Param("areaId") String areaId) {
		return indicatorService.checkUpdateIndicator(id, areaId);
	}

	/**
	 * 修改指标值
	 * */
	@At("/audit/updateIndicator")
	@Ok("json")
	public String updateIndicator(@Param("..") IndicatorDataVO indiVo) {
		return indicatorService.updateIndicator(indiVo);
	}

	/**
	 * 修改指标修正值
	 * */
	@At("/audit/updateIndicatorAccount")
	@Ok("json")
	public String updateIndicatorAccount(@Param("..") IndicatorAccountVO indiVo) {
		return indicatorService.updateIndicatorAccount(indiVo);
	}

	/**
	 * 查询指标修正值
	 * */
	@At("/audit/queryIndicatorAccount")
	@Ok("json")
	public List<IndicatorAccount> queryIndicatorAccount(@Param("..") IndicatorAccountVO indiVo) {
		return indicatorService.queryIndicatorAccount(indiVo);
	}

	
	/**
	 * 核算指标
	 */
	@At("/audit/initIndicatorAccount")
	@Ok("json")
	public String indicatorAccount(@Param("..") IndicatorAccountVO vo) {
		indicatorService.indicatorAccount(vo);
		return "1";
	}

	/**
	 * 核算单独指标
	 */
	@At("/audit/calculateSingleIndicator")
	@Ok("json")
	public String calculateSingleIndicator(@Param("id") String id) {
		indicatorService.calculateSingleIndicator(id);
		return "1";
	}
	
	/**
	 * 生成评估指标
	 */
	@At("/audit/indicatorEvaluation")
	@Ok("json")
	public String indicatorEvaluation(@Param("..") IndicatorAccountVO vo) {
		indicatorService.indicatorEvaluation(vo, 1);
		return "1";
	}
	
	/**
	 * 查询指标核算详情
	 */
	@At("/audit/indicatorProcess/?")
	@Ok("jsp:/static/ocean/audit/indicatorProcess")
	public List<Map> getIndicatorProcess(String id) {
		return indicatorService.getIndicatorProcess(id);
	}
	
	
	/**
	 * 查询指标核算详情
	 */
	@At("/audit/indicatorProcessSub/?/?/?")
	@Ok("jsp:/static/ocean/audit/indicatorProcess")
	public List<Map> getIndicatorProcess(String id, String year, String areaId) {
		return indicatorService.getIndicatorProcessSub(id, year, areaId);
	}
	
	/**
	 * 查询评估指标
	 */
	@At("/audit/queryIndicatorEvaluation")
	@Ok("json")
	public ResultVO<IndicatorAccountVO> queryIndicatorEvaluation(@Param("..") IndicatorAccountVO indiVo, @Param("page") Integer pageNum, @Param("rows") int rows) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, rows);
		}
		cn.com.generaldata.os.paging.Result list = indicatorService.queryIndicatorEvaluation(indiVo, page);
		ResultVO<IndicatorAccountVO> result = new ResultVO<IndicatorAccountVO>();
		List<IndicatorAccountVO> operationResult = new ArrayList<IndicatorAccountVO>();
		if (list != null) {
			operationResult = (List<IndicatorAccountVO>) list.getOperationResult();
			result.setPageNumber(list.getPageNumber());
			result.setPageSize(list.getPageSize());
			result.setTotalCount(list.getTotalCount());
		} else {
			result.setPageNumber(page.getPageNumber());
			result.setPageSize(page.getPageSize());
			result.setTotalCount(0);
		}
		result.setOperationResult(operationResult);
		return result;

	}
	
	/**
	 * 进入查询评估指标页面
	 */
	@At("/audit/indicatorAssessToPage/?/?")
	@Ok("jsp:/static/ocean/audit/indicatorAssess")
	public void queryIndicatorAssessToPage(String typeName, String subType, HttpServletRequest request) {
		
		request.setAttribute("typeName", typeName);
		request.setAttribute("subType", subType);
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型

	}
	
	/**
	 * 进入评估指标维护页面
	 */
	@At("/audit/indicatorInputAnToPage")
	@Ok("jsp:/static/ocean/audit/indicatorInputAn")
	public void queryIndicatorInputAnToPage(HttpServletRequest request) {
		
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型
		request.setAttribute("indicatorType", indicatorService.queryType());	//指标分类
		request.setAttribute("industryList", industryService.queryAllDLIndustries());	//产业分类
	}
	
	/**
	 * 指标查询（选择指标）
	 * */
	@At("/audit/queryIndicatorSelect")
	@Ok("jsp:/static/ocean/audit/indicatorSelect")
	public ResultVO<IndicatorDataVO> queryIndicatorSelect(@Param("p") Integer pageNum, HttpServletRequest request){
		
		request.setAttribute("typeList", reportService.queryType());	//报表制度类型
		
		return null;
	}
	
	private Map<String, AreaVO> listToMap(List<AreaVO> list){
		Map<String, AreaVO> tempMap = new HashMap<String, AreaVO>();
		for (AreaVO vo : list){
			tempMap.put(vo.getId(), vo);
		}
		return tempMap;
	}
}
